package com.weiqiao.mall.service.impl;


import com.google.gson.Gson;
import com.mingsoft.util.StringUtil;
import com.mongodb.client.model.Filters;
import com.weiqiao.mall.domain.CardCommodityEntity;
import com.weiqiao.mall.domain.TeamCommodityEntity;
import com.weiqiao.mall.domain.TeamEntity;
import com.weiqiao.mall.repository.ITeamCommodityRepository;
import com.weiqiao.mall.repository.ITeamRepository;
import com.weiqiao.mall.service.ITeamCommodityService;
import com.weiqiao.mall.service.vo.UpdateTeamCommodityDistributorInfoVO;
import com.weiqiao.mall.service.vo.UpdateTeamCommodityVO;
import com.weiqiao.utils.DateUtil;
import com.weiqiao.utils.SecurityUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.bson.Document;
import org.bson.conversions.Bson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import java.util.*;

@Service("TeamCommodityServiceImpl")
public class TeamCommodityServiceImpl implements ITeamCommodityService {

    @Autowired
    private ITeamCommodityRepository teamCommodityRepository;

    @Autowired
    private ITeamRepository teamRepository;


    @Override
    public int countCommodity(int companyId, Bson bson) {
        return teamCommodityRepository.countCommodity(companyId, bson);
    }

    @Override
    public List<TeamCommodityEntity> findCommoditys(int companyId, Bson filter) {
        List<TeamCommodityEntity> commodity = new ArrayList<>();
        List<String> list = teamCommodityRepository.findCommoditys(companyId, filter);
        for (String a : list) {
            TeamCommodityEntity c = new Gson().fromJson(a, TeamCommodityEntity.class);
            if (StringUtil.isLong(c.getCreate_date())) {
                c.setCreate_date(DateUtil.timestampToString(c.getCreate_date()));
            }
            commodity.add(c);
        }
        return commodity;
    }

    @Override
    public Map getCommodityTeamInfo(int companyId, Bson filter) {
        Map map = new HashMap();
        List<TeamEntity> list = new ArrayList<>();
        // 查找当前商品所关联的团队id
        List<TeamCommodityEntity>  array = findCommoditys(companyId, filter);
        if (CollectionUtils.isEmpty(array)) return map;
        List<String> teamIdList = new ArrayList<>();
        array.forEach(info -> {
            teamIdList.add(info.getTeam_id());
        });
        // 根据团队id，查找团队列表
        Bson teamFilter = new Document("team_id", new Document("$in", teamIdList));
        List<String> teamArray = teamRepository.getList(teamFilter, companyId);
        if (CollectionUtils.isEmpty(teamArray)) return map;
        Gson gson = new Gson();
        teamArray.forEach(info -> {
            TeamEntity entity = gson.fromJson(info, TeamEntity.class);
            list.add(entity);
        });
        // 当前商品所在团队
        map.put("list", list);
        // 团队佣金
        map.put("team_total", array.get(0).getTeam_total());
        return map;
    }

    @Override
    public List<TeamCommodityEntity> findCommoditys(int company_id, Document doc, Pageable pageable) {
        List<TeamCommodityEntity> commodityList = new ArrayList<>();
        List<String> list = teamCommodityRepository.findCommodityByFilterAndPage(company_id, doc, pageable);
        if (!list.isEmpty()) {
            for (String a : list) {
                TeamCommodityEntity c = new Gson().fromJson(a, TeamCommodityEntity.class);
                if (StringUtil.isLong(c.getCreate_date())) {
                    c.setCreate_date(DateUtil.timestampToString(c.getCreate_date()));
                }
                commodityList.add(c);
            }
        }
        return commodityList;
    }

    @Override
    public TeamCommodityEntity findCommodityById(String commodity_id, int company_id) {
        Bson filter = Filters.eq("commodity_id", commodity_id);
        String s = teamCommodityRepository.findCommodityById(company_id, filter);
        return new Gson().fromJson(s, TeamCommodityEntity.class);
    }

    @Override
    public boolean detCardCommodity(String commodity_id, int company_id) {
        Bson filter = Filters.eq("commodity_id", commodity_id);
        teamCommodityRepository.updateOneCommodity(company_id, filter, new Document("delete_flag", 1), false);
        return true;
    }

    @Override
    public boolean delTeamCommodity(int companyId, CardCommodityEntity commodity) {
        // 因为产品在发生编辑时，运营者也可能会发生变动，所以，在运营者减少时，需要把减少的运营者相关联的团队信息同步删除
        Document filter = new Document("commodity_id", commodity.getCommodity_id());
        if (CollectionUtils.isNotEmpty(commodity.getOperator_list())) {
            List<Integer> idList = new ArrayList<>();
            commodity.getOperator_list().forEach(info -> {
                idList.add(info.getUser_id());
            });
            filter.append("operator_id", new Document("$ne", idList));
        }
        return teamCommodityRepository.delMany(companyId, filter);
    }


    @Override
    public boolean updateCommodity(int companyId, Bson filter, Document doc) {
        return teamCommodityRepository.updateMany(companyId, filter, doc, false);
    }

    @Override
    public boolean updateCommodityTeamInfo(UpdateTeamCommodityVO entity) {
        // 逻辑：1.判断是系统管理员还是省长
        // 2.系统管理员看是可以看到当前商品所有的团队的，那么，编辑或修改当前商品的所有的团队
        // 3.省长只能看到当前商品自己创建的团队，那么编辑或修改当前商品的分销佣金
        // 操作：1.假删除所有的相关联的团队信息；2.被编辑到的商品逐个释放，释放假删除 3.真删除未被释放的假删除商品
        // 查询条件
        Document filter = new Document("commodity_id", new Document("$in", entity.getCommodity_id_list()));
        if (entity.getOperator_id() != 0) {
            // 省长
            filter.append("operator_id", entity.getOperator_id());
        }
        // 假删除
        teamCommodityRepository.updateMany(entity.getCompany_id(), filter, new Document("delete_flag", 1), false);
        // 有则编辑假删除状态，没有则新增
        if (CollectionUtils.isNotEmpty(entity.getTeam_commodity_list())) {
            Gson gson = new Gson();
            entity.getTeam_commodity_list().forEach(info -> {
                Bson updateFilter = new Document("team_id", info.getTeam_id()).append("commodity_id", info.getCommodity_id());
                Document update = Document.parse(gson.toJson(info));
                teamCommodityRepository.updateOneCommodity(entity.getCompany_id(), updateFilter, update, true);
            });
        }
       // 真删除所有假删除的内容
        filter.append("delete_flag", 1);
        teamCommodityRepository.delMany(entity.getCompany_id(), filter);
        return true;
    }

    @Override
    public boolean updateCommodityDistributorInfo(UpdateTeamCommodityDistributorInfoVO entity) {
        // 逻辑：因为获取到的商品都是团商品，最小单位是团。就算是省长、分销员，那么看到的团商品是同一商品会出现多次，即一个商品对应多个团
        // 那么更新时，必定是团id，商品id为查询条件，更新分销佣金
        if (CollectionUtils.isNotEmpty(entity.getTeam_commodity_list())) {
            // 单个更新，不然只能用or查询条件，不建议，故for循序，单个进行更新
            entity.getTeam_commodity_list().forEach(info -> {
                Document filter = new Document("commodity_id", info.getCommodity_id()).append("team_id", info.getTeam_id());
                Document update = new Document("distribution_total", entity.getDistribution_total());
                teamCommodityRepository.updateOneCommodity(entity.getCompany_id(), filter, update, false);
            });
        }
        return true;
    }


}
